<template>
  <div>
    <el-card style="margin: 15px; min-height: 600px">
      <el-button
        @click="addTest"
        v-if="isAdminAll"
        icon="el-icon-plus"
        type="primary"
        size="large"
        style="margin-bottom: 20px"
        :disabled="disabled"
        >添加考试</el-button
      >
      <el-empty
        v-if="sense == 1 && !testList.length"
        description="暂无考试"
        :image-size="220"
      ></el-empty>
      <el-table
        v-if="sense == 1 && testList.length"
        :data="testList"
        style="width: 100%"
        @cell-click="enterTesting"
      >
        <el-table-column type="index" label="序号" width="100">
        </el-table-column>
        <el-table-column prop="title" label="名称"> </el-table-column>
        <el-table-column prop="formatStartTime" label="开始时间">
        </el-table-column>
        <el-table-column prop="formatEndTime" label="结束时间">
        </el-table-column>
        <el-table-column prop="submitTimes" label="可提交次数">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="{ row, $index }">
            <span v-if="row.isDone == 1" style="color: #f56c6c">已结束</span>
            <span v-if="row.isDone == -1" style="color: #909399">未开始</span>
            <span v-if="row.isDone == 0" style="color: #67c23a">进行中</span>
          </template>
        </el-table-column>
        <el-table-column v-if="isAdminAll" label="操作">
          <template slot-scope="{ $index, row }">
            <el-button
              @click="updateTest(row, $index)"
              icon="el-icon-edit"
              type="warning"
              size="mini"
            ></el-button>
            <el-button
              @click="deleteTest(row, $index)"
              icon="el-icon-delete"
              type="danger"
              size="mini"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="sense == 2">
        <el-form
          ref="test"
          style="margin-left: 10px"
          :model="test"
          label-width="80px"
          label-position="right"
          :rules="testRules"
        >
          <el-form-item prop="title" label="考试标题">
            <el-col :span="15">
              <el-input
                placeholder="请输入标题"
                type="textarea"
                :rows="4"
                :maxlength="80"
                show-word-limit
                v-model="test.title"
              ></el-input>
            </el-col>
          </el-form-item>

          <el-form-item prop="time" label="起始时间">
            <el-col :span="15">
              <el-date-picker
                type="datetimerange"
                v-model="test.time"
                :picker-options="pickerOptions"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                range-separator="至"
                value-format="timestamp"
                align="left"
                style="width: 100%"
              ></el-date-picker>
            </el-col>
          </el-form-item>

          <el-form-item prop="submitTimes" label="提交次数">
            <el-col :span="5">
              <el-input
                v-model="test.submitTimes"
                :rows="5"
                placeholder="次数不能小于1"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="注意事项">
            <el-col :span="15">
              <el-input
                v-model="test.attention"
                :rows="5"
                placeholder="可以不填"
                type="textarea"
              ></el-input>
            </el-col>
          </el-form-item>
        </el-form>

        <div style="width: 100%; position: relative; height: 40px">
          <div style="position: absolute; right: 18px">
            <el-button type="primary" @click="addTestList" icon="el-icon-plus"
              >题目</el-button
            >
            <el-button @click="cancelAddTest">取消</el-button>
          </div>
        </div>

        <div style="position: relative">
          <div
            v-for="(item, index) in test.items"
            :key="item.itemTitle + item.itemContent"
            @click="showTestDetail(item,index)"
          >
            <TestDetail
              :testData="item"
              :index="index + 1"
              :deleteBtnShow="true"
              style="margin: 15px"
              @delete="deleteTestDetailList"
            ></TestDetail>
          </div>
        </div>

        <div
          v-show="test.items.length"
          style="width: 100%; position: relative; height: 40px"
        >
          <div style="position: absolute; right: 18px">
            <el-button type="primary" @click="publishTest">发布</el-button>
            <el-button @click="cancelAddTest">取消</el-button>
          </div>
        </div>
      </div>

      <el-dialog title="题目" :visible.sync="dialogFormVisible">
        <el-form
          style="margin-left: 10px"
          :model="testDetail"
          ref="testDetail"
          size="normal"
          label-width="80px"
          label-position="right"
          :rules="testDetailRules"
        >
          <el-form-item prop="itemTitle" label="题目标题">
            <el-col :span="19">
              <el-input
                type="textarea"
                show-word-limit
                :rows="4"
                :maxlength="80"
                v-model="testDetail.itemTitle"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item prop="score" label="分值">
            <el-col :span="5">
              <el-input v-model="testDetail.score"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item prop="itemContent" label="题目内容">
            <el-col :span="19">
              <el-input
                :rows="6"
                :maxlength="2000"
                show-word-limit
                v-model="testDetail.itemContent"
                type="textarea"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="内容图片" prop="contentPic">
            <el-upload
              action="papi/file/upload"
              list-type="picture-card"
              :file-list="testDetail.contentPic"
              :on-remove="handleRemoveContent"
              :before-upload="PicBeforeUpload"
              :headers="headers"
              name="myfile"
              :on-success="uploadSuccessContent"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item prop="resultExample" label="结果演示">
            <el-col :span="19">
              <el-input
                :rows="6"
                :maxlength="2000"
                show-word-limit
                type="textarea"
                v-model="testDetail.resultExample"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="演示图片" prop="resultExamplePic">
            <el-upload
              action="papi/file/upload"
              list-type="picture-card"
              :on-remove="handleRemoveResult"
              :before-upload="PicBeforeUpload"
              :headers="headers"
              name="myfile"
              :file-list="testDetail.resultExamplePic"
              :on-success="uploadSuccessResult"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="文件" prop="file">
            <el-upload
              action="papi/file/upload"
              :on-remove="handleRemoveFile"
              :before-upload="textBeforeUpload"
              name="myfile"
              :limit="1"
              :headers="headers"
              :on-exceed="handleExceed"
              :file-list="testDetail.file"
              :on-success="uploadSuccessFile"
            >
              <el-button size="small" type="primary" icon="el-icon-plus"
                >附件</el-button
              >
              <div slot="tip" class="el-upload__tip">文件大小不超过10M</div>
            </el-upload>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelAddTestDetail">取 消</el-button>
          <el-button type="primary" @click="confirmAddTestDetail"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import store from "@/store";
import dayjs from "dayjs";
import TestDetail from "@/components/testDetail/index";
export default {
  components: {
    TestDetail,
  },
  data() {
    return {
      testList: [],
      sense: 1,
      isEdit: {state:false,index:0},
      test: {
        title: "",
        attention: "",
        createTime: 0,
        submitTimes: 1,
        time: [],
        items: [],
      },
      testDetail: {
        itemTitle: "",
        itemContent: "",
        score: 0,
        contentPic: [],
        resultExamplePic: [],
        resultExample: "",
        file: [],
      },
      testRules: {
        title: [
          {
            required: true,
            message: "标题不能为空",
            trigger: "blur",
          },
        ],
        time: [
          {
            required: true,
            message: "起始时间不能为空",
            trigger: "blur",
          },
        ],
        submitTimes: [
          {
            required: true,
            message: "提交次数不能为空",
            trigger: "blur",
          },
        ],
      },
      testDetailRules: {
        itemTitle: [
          {
            required: true,
            message: "标题不能为空",
            trigger: "blur",
          },
        ],
        itemContent: [
          {
            required: true,
            message: "题目内容不能为空",
            trigger: "blur",
          },
        ],
        score: [
          {
            required: true,
            message: "分值不能为空",
            trigger: "blur",
          },
        ],
      },
      disabled: false,
      dialogFormVisible: false,
      //时间选择器限制时间选项
      pickerOptions: {
        disabledDate: (time) => {
          let todayTimestamp = new Date(
            new Date().toLocaleDateString()
          ).getTime();
          let timeRange = time.getTime() < todayTimestamp;
          return timeRange;
        },
      },
    };
  },

  methods: {
    async getTestList() {
      const res = await this.$API.test.getTestList();
      if (res.code == 200) {
        const list = res.data;
        list.forEach((item) => {
          item.formatStartTime = dayjs(item.startTime).format(
            "YYYY-MM-DD hh:mm:ss"
          );
          item.formatEndTime = dayjs(item.endTime).format(
            "YYYY-MM-DD hh:mm:ss"
          );
        });
        this.testList = list;
      }
    },
    submitForm(formName, func) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          func();
        } else {
          return false;
        }
      });
    },
    gotoSense1() {
      this.resetForm("test");
      this.test.items = [];
      this.sense = 1;
      this.disabled = false;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addTest() {
      this.sense = 2;
      this.disabled = true;
    },
    deleteTest(row, $index) {
      this.$confirm("是否删除当前选中的考试?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return this.$API.test.deleteTest(row.id);
        })
        .then(() => {
          this.$message.success("删除成功");
          this.getTestList();
        });
    },
    cancelAddTest() {
      this.gotoSense1();
    },
    addTestList() {
      this.submitForm("test", () => {
        this.dialogFormVisible = true;
      });
    },
    confirmAddTestDetail() {
      this.submitForm("testDetail", () => {
        if (this.isEdit.state == false) {
          this.test.items.push(JSON.parse(JSON.stringify(this.testDetail)));
          this.dialogFormVisible = false;
          this.resetForm("testDetail");
        }else{
          this.$set(this.test.items,this.isEdit.index,JSON.parse(JSON.stringify(this.testDetail)))
          this.dialogFormVisible = false;
          this.resetForm("testDetail");
          this.isEdit.state = false;
        }
      });
    },
    cancelAddTestDetail() {
      this.resetForm("testDetail");
      this.dialogFormVisible = false;
      this.isEdit.state = false;
    },
    showTestDetail(item,index) {
      this.testDetail = JSON.parse(JSON.stringify(item));
      this.isEdit.state = true;
      this.isEdit.index = index
      this.dialogFormVisible = true;
    },
    handleRemoveContent(file, fileList) {
      this.testDetail.contentPic.splice(
        this.testDetail.contentPic.indexOf(file),
        1
      );
    },
    handleRemoveResult(file, fileList) {
      this.testDetail.resultExamplePic.splice(
        this.testDetail.resultExamplePic.indexOf(file),
        1
      );
    },
    handleRemoveFile(file, fileList) {
      this.testDetail.file.splice(this.testDetail.file.indexOf(file), 1);
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传一个文件");
    },
    BeforeUpload(file, format, size) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const str = format.join("、");
      if (format.indexOf(fileSuffix) === -1) {
        this.$message(`上传文件只能是${str}格式`, "error");
        return false;
      }
      const limit = file.size / 1024 / 1024 < size;
      if (!limit) {
        this.$msg(`上传文件大小不能超过${size}MB`, "error");
        return false;
      }
    },
    uploadSuccessContent(response, file, fileList) {
      this.testDetail.contentPic.push(response);
    },
    uploadSuccessResult(response, file, fileList) {
      this.testDetail.resultExamplePic.push(response);
    },
    uploadSuccessFile(response, file, fileList) {
      this.testDetail.file.push(response);
    },
    textBeforeUpload(file) {
      return this.BeforeUpload(
        file,
        ["pdf", "doc", "docx", "txt", "zip", "rar", "7z"],
        5
      );
    },
    PicBeforeUpload(file) {
      return this.BeforeUpload(file, ["jpg", "png"], 2);
    },
    deleteTestDetailList(index) {
      this.test.items.splice(index, 1);
    },
    publishTest() {
      this.$confirm("是否发布?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(() => {
          this.test.createTime = Date.now();
          return this.$API.test.publishTest(this.test);
        })
        .then((res) => {
          this.$message.success("发布成功");
          this.gotoSense1();
          this.getTestList();
        });
    },
    enterTesting(row, column) {
      if (column.label !== "操作") {
        if (
          this.$store.state.user.roles != "总管理员" &&
          Date.now() < row.startTime
        ) {
          return this.$message.warning("考试暂未开始");
        }
        this.$router.push({
          name: "Testing",
          params: {
            testId: row.id,
          },
        });
      }
    },
  },
  mounted() {
    this.getTestList();
  },
  computed: {
    isAdminAll() {
      return store.getters.roles == "总管理员" ? true : false;
    },
    headers() {
      return {
        Authorization: this.$store.getters.token,
      };
    },
  },
};
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
<style scoped>
.line {
  text-align: center;
}
</style>
